//
//  MyHomeViewController.swift
//  weibo08
//
//  Created by 陈杰明 on 16/2/27.
//  Copyright © 2016年 JM. All rights reserved.
//

import UIKit
class MyHomeViewController: MyBaseTableViewController {
    
    
    private let reuseIdentifier = "cell"
    //定义微博属性
    var status: [MyStatus]?{
        didSet{
        //当别人赋值后再刷新
        tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //只有用户登录了才做下面操作
        if !MyUserAccountViewModel.sharedInstance.userLogin {
            return
        }
        
        loadStatus()
        //注册
        tableView.registerClass(MyStatusCell.self, forCellReuseIdentifier: reuseIdentifier)
        setupNavigationBar()
        
        //设置预估行高
        //设置rowHeight = UITableViewAutomaticDimension
        //设置好约束contentView
        tableView.estimatedRowHeight = 150
        tableView.rowHeight = UITableViewAutomaticDimension
        
    }
    
    func loadStatus() {
        
//        MyNetWorkTool.sharedInstance.loadStatus { (result, error) -> () in
//            if error != nil {
//                MyNetWorkToolError.AccessTokenEmpty.error()
//                return
//            }
//            
//            print("\n\t微博数据:\(result)")
//        }
        StatusVM.loadSatus { (status, error) -> () in
            if error != nil {
                MyNetWorkToolError.AccessTokenEmpty.error()
                return
            }
            print("在控制器中打印微博数据: \(status)")
            self.status = status
            
            
        }
    }
    //设置导航栏
    private func setupNavigationBar() {
        setupBarButtonItem()
//        setupTitleView()
        //设置标题
        if let screen_name = MyUserAccountViewModel.sharedInstance.userAccount?.screen_name {
            
            self.setupTitleView(screen_name)
        }
        
        MyNetWorkTool.sharedInstance.loadUserInfo { (result, error) -> () in
            if error != nil {
                print("screen_name出错啦")
                return
            }
            
            if let screen_name = MyUserAccountViewModel.sharedInstance.userAccount?.screen_name {
                
                self.setupTitleView(screen_name)
            }
        }
    }
    private func setupBarButtonItem() {
    //左边按钮
//    let leftButton = UIButton()
//        leftButton.setBackgroundImage(UIImage(named: "navigationbar_friendsearch"), forState: UIControlState.Normal)
//        leftButton.setBackgroundImage(UIImage(named: "navigationbar_friendsearch_highlighted"), forState: UIControlState.Highlighted)
//        leftButton.sizeToFit()
    //右边按钮
//    let rightButton = UIButton()
//        rightButton.setBackgroundImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
//        rightButton.setBackgroundImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted)
//        rightButton.sizeToFit()
//        let rightButton = creatBarButtonItem("navigationbar_pop")
      
//    self.navigationItem.leftBarButtonItem = creatBarButtonItem("navigationbar_friendsearch")
//    self.navigationItem.rightBarButtonItem = creatBarButtonItem("navigationbar_pop")
        
//        self.navigationItem.leftBarButtonItem = UIBarButtonItem.creatBarButtonItem("navigationbar_friendsearch")
//        self.navigationItem.rightBarButtonItem = UIBarButtonItem.creatBarButtonItem("navigationbar_pop")
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(name: "navigationbar_friendsearch")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(name: "navigationbar_pop")
    }
    //创建UIBarButtonItem
    private func creatBarButtonItem(name: String) -> UIBarButtonItem{
        let button = UIButton()
        button.setBackgroundImage(UIImage(named: name), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "\(name)_highlighted"), forState: UIControlState.Highlighted)
        button.sizeToFit()
    
        return UIBarButtonItem(customView: button)
    }
    
    private func setupTitleView(name: String) {
    
        let button = MyTitleView(name: name)
        
        button.addTarget(self, action: "buttonDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = button
    }
    
    func buttonDidClick(button: UIButton) {
    
        button.selected = !button.selected
        
//        if button.selected {
//            
//            UIView.animateWithDuration(0.25, animations: { () -> Void in
//                button.imageView?.transform = CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001))
//            })
//            
//        }else {
//            UIView.animateWithDuration(0.25, animations: { () -> Void in
//                
//                button.imageView?.transform = CGAffineTransformIdentity
//            })
//        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) : CGAffineTransformIdentity
        }
        
        if button.selected {
        //创建sb
        let sb = UIStoryboard(name: "Popover", bundle: nil)
        //创建控制器
        let popoverVC = sb.instantiateViewControllerWithIdentifier("popover")
      
        popoverVC.modalPresentationStyle = UIModalPresentationStyle.Popover
        //设置代理
        popoverVC.popoverPresentationController?.delegate = self
        
        popoverVC.popoverPresentationController?.sourceView = navigationItem.titleView
        popoverVC.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds
        //设置弹出控制器大小
            popoverVC.preferredContentSize = CGSize(width: 200, height: 5 * 44)
        //modal控制器
        self.presentViewController(popoverVC, animated: true, completion: nil)
        }
    }
    
    lazy var StatusVM: MyStatusViewModel = MyStatusViewModel()
}

extension MyHomeViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.status?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyStatusCell
        
        //将微博内容显示出来
        cell.status = status?[indexPath.row]
        
        
        return cell
    }

}

extension MyHomeViewController: UIPopoverPresentationControllerDelegate {
    //让iPhone可以显示popover效果
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }

    //popover关闭时调用
    func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
        
        let button = navigationItem.titleView as! MyTitleView
        buttonDidClick(button)
    }
//    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
//        print("完成1")
//        let button = navigationItem.titleView as! MyTitleView
//        buttonDidClick(button)
//        return true
//    }
}